#!/bin/bash

# Docker Compose 应用打包脚本
set -e

# 简化日志函数
log() { echo "⏰ [$(date +'%H:%M:%S')] $1" >&2; }
error() { echo "❌ [ERROR] $1" >&2; exit 1; }

# 检查 Docker
! docker info >/dev/null 2>&1 && error "Docker 未运行"

# 发现项目相关的数据卷
find_project_volumes() {
    local app_dir="$1"
    local project_name=$(basename "$app_dir")
    
    log "🔍 搜索项目相关数据卷 (前缀: $project_name)"
    docker volume ls --format "{{.Name}}" | grep "^${project_name}[_-]" || true
}

# 导出数据卷
export_volume() {
    local volume="$1" backup_dir="$2"
    log "💾 导出数据卷: $volume"
    docker run --rm -v "$volume:/data" -v "$backup_dir:/backup" alpine \
        sh -c "cd /data && tar czf /backup/${volume}.tar.gz ."
}

# 打包应用目录
package_app() {
    local app_dir="$1" backup_dir="$2" app_name="$3"
    log "📦 打包应用目录: $app_dir"
    tar czf "${backup_dir}/${app_name}_app.tar.gz" -C "$(dirname "$app_dir")" "$(basename "$app_dir")"
}

# 创建最终压缩包
create_package() {
    local backup_dir="$1" app_name="$2" output_dir="$3"
    log "🗜️ 创建最终压缩包"
    tar czf "${output_dir}/${app_name}.tar.gz" -C "$backup_dir" .
}

# 上传到服务器
upload_file() {
    local file="$1" server="$2"
    [[ -z "$server" ]] && return 0
    log "🚀 上传到服务器: $server"
    scp "$file" "$server"
}

# 主函数
main() {
    echo "🐳 === Docker Compose 应用打包工具 === 🐳"
    echo
    
    # 获取输入
    read -p "📁 应用目录路径: " app_dir
    [[ ! -d "$app_dir" ]] && error "目录不存在: $app_dir"
    
    app_name=$(basename "$app_dir")
    read -p "📦 应用名称 [$app_name]: " input_name
    [[ -n "$input_name" ]] && app_name="$input_name"
    
    # 自动发现数据卷
    auto_volumes=($(find_project_volumes "$app_dir"))
    echo "💾 发现数据卷:"
    if [[ ${#auto_volumes[@]} -eq 0 || (${#auto_volumes[@]} -eq 1 && -z "${auto_volumes[0]}") ]]; then
        echo "   └── 无"
    else
        for vol in "${auto_volumes[@]}"; do
            [[ -n "$vol" ]] && echo "   └── $vol"
        done
    fi
    
    read -p "➕ 额外数据卷 (空格分隔): " extra_volumes
    volumes=(${auto_volumes[@]} $extra_volumes)
    
    read -p "🌐 上传服务器 (user@host:/path): " server
    
    # 显示摘要
    echo
    echo "📋 === 操作摘要 ==="
    echo "📂 应用目录: $app_dir"
    echo "📦 输出文件: ${app_name}.tar.gz"
    echo "💾 数据卷:"
    if [[ ${#volumes[@]} -eq 0 || (${#volumes[@]} -eq 1 && -z "${volumes[0]}") ]]; then
        echo "   └── 无"
    else
        for vol in "${volumes[@]}"; do
            [[ -n "$vol" ]] && echo "   └── $vol"
        done
    fi
    echo "🌐 上传服务器: ${server:-无}"
    echo
    
    read -p "✅ 确认执行? (y/N): " confirm
    [[ "$confirm" != [yY] ]] && exit 0
    
    # 执行备份
    backup_dir="/tmp/backup_$$"
    mkdir -p "$backup_dir"
    trap "rm -rf '$backup_dir'" EXIT
    
    # 打包应用
    package_app "$app_dir" "$backup_dir" "$app_name"
    
    # 导出数据卷
    for vol in "${volumes[@]}"; do
        [[ -n "$vol" ]] && export_volume "$vol" "$backup_dir"
    done
    
    # 创建最终包
    output_file="${app_name}.tar.gz"
    create_package "$backup_dir" "$app_name" "$(pwd)"
    
    # 上传
    upload_file "$output_file" "$server"
    
    echo
    echo "🎉 === 备份完成! ==="
    echo "📁 文件: $output_file"
    echo "📏 大小: $(du -h "$output_file" | cut -f1)"
    echo "✨ 备份成功完成! ✨"
}

# 运行主函数
main "$@"